// 给定一个整数数组nums和一个目标值target，要求从nums中选出三个整数，使它们的和与target最接近，返回这三个数的和，假定每组输入只存在恰好一个解
// 思路，双指针法

function threeSumClosest(nums, target) {
    nums.sort((a, b) => a - b)
    let res = Infinity
    for (let i = 2; i < nums.length; i++) {
        let left = 0
        let right = i - 1
        while (left < right) {
            let sum = nums[left] + nums[right] + nums[i]
            if (Math.abs(sum - target) < Math.abs(res - target)) {
                res = sum
            }
            if (sum > target) {
                right--
            } else {
                left++
            }
        }
    }
    return res
}

function threeSumClosest2(nums, target) {
    nums.sort((a, b) => a - b)
    let res = Infinity
    for (let i = 0; i < nums.length; i++) {
        let left = i + 1
        let right = nums.length - 1
        while (left < right) {
            let sum = nums[left] + nums[right] + nums[i]
            if (Math.abs(sum - target) < Math.abs(res - target)) {
                res = sum
            }
            if (sum > target) {
                right--
            } else {
                left++
            }
        }
    }
    return res
}

let nums = [-1, 2, 1, -4], target = 1
console.log(threeSumClosest(nums, target))